package com.example.worklab.pathmeasure.widget

import android.content.Context
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PathMeasure
import android.view.View

class BoatWaveView @JvmOverloads constructor(
    context: Context,
    attrs: android.util.AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private var mWidth = 0
    private var mHeight = 0
    private var WAVE_LENGTH = 0

    //小船浪花高度
    private val BOAT_WAVE_HEIGHT = 20

    //浪花高度
    private val WAVE_HEIGHT = 35

    //浪花每次偏移量
    private val WAVE_OFFSET = 5

    private val mBoatPath = Path()
    private val mWavePath = Path()
    private val mBoatWavePath = Path()

    private val mBoatPathMeasure = PathMeasure()

    private val mWavePaint = Paint().apply {
        isAntiAlias = true
    }

    private var isInit = false
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        if (!isInit) {
            isInit = true

            mWidth = measuredWidth
            mHeight = measuredHeight

            WAVE_LENGTH = mWidth / 2

            //初始化小船的浪路径
            initPath(mBoatWavePath, WAVE_LENGTH, BOAT_WAVE_HEIGHT, true, 2)
            //初始化浪路径
            initPath(mWavePath, WAVE_LENGTH, WAVE_HEIGHT, true, 2)
            //初始化小船的路径
            initPath(mBoatPath, WAVE_LENGTH, BOAT_WAVE_HEIGHT, false, 1)

            mBoatPathMeasure.setPath(mBoatPath, false)
        }
    }

    /**
     * @param path       绘制路径
     * @param length     浪花宽度
     * @param height     浪花高度
     * @param isClose    是否闭合
     * @param lengthTime 浪花长的倍数
     */
    private fun initPath(
        path: Path,
        length: Int,
        height: Int,
        isClose: Boolean,
        lengthTime: Int
    ) {
        path.moveTo(-length * 1.0f, mHeight * 1.0f / 2)
        var i = -length * 1.0f
        while (i < mWidth * lengthTime + length) {
            path.rQuadTo(length * 1.0f / 4, -height * 1.0f, length * 1.0f / 2, 0f)
            path.rQuadTo(length * 1.0f / 4, height * 1.0f, length * 1.0f / 2, 0f)
            i += length
        }

        if (isClose) {
            path.rLineTo(0f, mHeight * 1.0f / 2)
            path.rLineTo(-(mWidth * 2 + 2 * length * 1.0f), 0f)
            path.close()
        }
    }
}